import { openViewChaptersModal,closeViewChaptersModal,checkRoleAndAddChapter,checkRoleAndDeleteChapter,addNewChapter,deleteChapter,closeAddChapterModal,closeDeleteChapterModal} from './chapter.js';
import { new_openViewResourcesModal,viewResources ,previewResource,downloadResource,closeAllVersionsModal,closeViewResourcesModal,openUploadResourceModal,closeUploadResourceModal,uploadResource} from './resource.js';
import { openCoursePreviewModal, closeCoursePreviewModal} from './course.js';
import { editProfile,logout,setupUserProfile} from "./auth.js";



window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
window.openViewChaptersModal = openViewChaptersModal;
window.closeViewChaptersModal = closeViewChaptersModal;
window.openCoursePreviewModal = openCoursePreviewModal;
window.closeCoursePreviewModal = closeCoursePreviewModal;
window.viewResources = viewResources;
window.previewResource = previewResource;
window.downloadResource = downloadResource;
window.closeAllVersionsModal = closeAllVersionsModal;
window.closeViewResourcesModal = closeViewResourcesModal;
window.checkRoleAndAddChapter = checkRoleAndAddChapter;
window.checkRoleAndDeleteChapter = checkRoleAndDeleteChapter;
window.openUploadResourceModal = openUploadResourceModal;
window.closeUploadResourceModal = closeUploadResourceModal;
window.addNewChapter = addNewChapter;
window.deleteChapter = deleteChapter;
window.closeAddChapterModal = closeAddChapterModal;
window.closeDeleteChapterModal = closeDeleteChapterModal;
window.uploadResource = uploadResource;
window.new_openViewResourcesModal = new_openViewResourcesModal;

// 页面加载完成后显示已选课程
window.onload = async function () {
    showCourses();
};

let filterDebounceTimer = null;

export async function showCourses() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        if (!username) {
            throw new Error('URL中缺少username参数');
        }
        await setupUserProfile(username);

        const response = await fetch(`/get-courses`);
        const courses = await response.json();
        const userResponse = await fetch(`/user-info?username=${username}`);
        const userData = await userResponse.json();
        const isTeacher = userData.role === '教师';
        
        // 添加筛选标志
        const showOnlyMyCourses = document.getElementById('myCoursesFilter')?.checked;

        const courseList = document.getElementById('courseList');
        courseList.innerHTML = '';
        
        // 获取学生已选课程
        const selectedCoursesResponse = await fetch(`/get-selected-courses?username=${username}`);
        const selectedCourses = await selectedCoursesResponse.json();
        
        // 获取搜索框的值
        const searchInput = document.getElementById('courseSearch');
        const searchTerm = searchInput ? searchInput.value.trim().toLowerCase() : '';

        let displayedCourses = 0; // 计数器，记录实际显示的课程数量

        for (const course of courses) {
            // 搜索过滤
            if (searchTerm && 
                !course.course_code.toLowerCase().includes(searchTerm) &&
                !course.course_name.toLowerCase().includes(searchTerm)) {
                continue;
            }

            // 教师课程过滤
            if (userData.role === '教师' && showOnlyMyCourses && course.teacher_user_id !== userData.user_id) {
                continue;
            }

            // 助教课程过滤
            if (userData.role === '助教' && showOnlyMyCourses && !await checkTutorPermission(userData.user_id, course.course_code)) {
                continue;
            }        
            
            const courseCode = course.course_code;
            const teacher_name_response = await fetch(`/user-info-by-id?userId=${course.teacher_user_id}`);
            const teacher_name_json = await teacher_name_response.json();
            const teacher_name = teacher_name_json.name;

            // 获取课程助教信息
            const tutorsResponse = await fetch(`/get-course-tutors?courseCode=${course.course_code}`);
            const tutors = await tutorsResponse.json();
            
            // 处理助教名字显示
            let tutorNamesDisplay = "暂无助教";
            if (tutors && tutors.length > 0) {
                tutorNamesDisplay = tutors.map(tutor => tutor.tutor_name).join(', ');
            }

            const courseBox = document.createElement('div');
            courseBox.classList.add('course-box');
            let buttonHtml = `
    <div class="button-group">
        <button class="action-btn chapter-btn" onclick="openViewChaptersModal('${course.course_code}')">
            <i class="fas fa-list-alt"></i>
            <span>查看章节</span>
        </button>
        
        <button class="action-btn resource-btn" onclick="new_openViewResourcesModal('${course.course_code}')">
            <i class="fas fa-folder-open"></i>
            <span>查看资源</span>
        </button>
        
        <button class="action-btn preview-btn" onclick="openCoursePreviewModal('${course.course_code}')">
            <i class="fas fa-play-circle"></i>
            <span>课程预览</span>
        </button>
`;

if ((isTeacher && course.teacher_user_id === userData.user_id) || 
    (userData.role === '助教' && await checkTutorPermission(userData.user_id, courseCode))) {
    buttonHtml += `
    <button class="action-btn add-chapter-btn" onclick="checkRoleAndAddChapter('${course.course_code}', '${course.teacher_user_id}')">
            <i class="fas fa-list-alt"></i>
            <span>新增章节</span>
    </button>

    <button class="action-btn delete-chapter-btn" onclick="checkRoleAndDeleteChapter('${course.course_code}', '${course.teacher_user_id}')">
            <i class="fas fa-list-alt"></i>
            <span>删除章节</span>
    </button>

    <button class="action-btn upload-resource-btn" onclick="openUploadResourceModal('${course.course_code}', '${course.teacher_user_id}')">
            <i class="fas fa-list-alt"></i>
            <span>上传资源</span>
    </button>
    </div>
    `;
} else if(!isTeacher) {
    const isCourseSelected = selectedCourses.some(c => c.course_code === course.course_code);
            if (isCourseSelected) {
                buttonHtml += `
                    <button class="action-btn drop-course-btn" onclick="dropCourse('${course.course_code}')">
                        <i class="fas fa-list-alt"></i>
                    <span>退选课程</span>
                    </button>
                    </div>
                `;
            } else {
                buttonHtml += `
                    <button class="action-btn select-course-btn" onclick="selectCourse('${course.course_code}')">
                        <i class="fas fa-list-alt"></i>
                    <span>选择课程</span>
                    </button>
                    </div>
                `;
            }
}
courseBox.innerHTML = `
<div class="course-header">
    <h3 class="course-title">
        <i class="fas fa-book-open text-primary"></i>
        <span class="text-gradient">${escapeHTML(course.course_code)}——${escapeHTML(course.course_name)}</span>
    </h3>
    <div class="course-meta">
        <span class="meta-item">
            <i class="fas fa-user-tie text-teacher"></i>
            <span class="meta-text">${escapeHTML(teacher_name)}</span>
        </span>
        <span class="meta-item">
            <i class="fas fa-clock text-time"></i>
            <span class="meta-text">${escapeHTML(course.course_time)}</span>
        </span>
        <span class="meta-item">
            <i class="fas fa-map-marker-alt text-location"></i>
            <span class="meta-text">${escapeHTML(course.place)}</span>
        </span>
        <span class="meta-item">
            <i class="fas fa-user-graduate text-tutor"></i>
            <span class="meta-text">课程助教：${escapeHTML(tutorNamesDisplay)}</span>
        </span>
    </div>
</div>

<div class="course-details">
    <div class="detail-card">
        <div class="detail-item">
            <i class="fas fa-star text-credits"></i>
            <span class="detail-label">课程学分</span>
            <span class="detail-value">${course.credits}</span>
        </div>
        <div class="detail-item">
            <i class="fas fa-hourglass-half text-period"></i>
            <span class="detail-label">课程学时</span>
            <span class="detail-value">${course.study_period}</span>
        </div>
        <div class="detail-item assessment-item">
                <div class="assessment-icon">
                    <i class="fas fa-clipboard-check text-assessment"></i>
                </div>
                <div class="assessment-content">
                    <div class="detail-label">考核方式</div>
                    <div class="detail-value assessment-value">${escapeHTML(course.assessment_method)}</div>
                </div>
            </div>
    </div>
    
    <div class="course-description">
        <p class="description-title">
            <i class="fas fa-bullseye text-objective"></i> 
            <span>教学目标</span>
        </p>
        <p class="description-content">${escapeHTML(course.teaching_objectives)}</p>
    </div>
    
    <div class="course-footer">
        <p class="weeks-info">
            <i class="fas fa-calendar-alt text-week"></i>
            <span>上课周次：${escapeHTML(course.teach_weeks)}</span>
        </p>
        <p class="toggle-tip">
            <i class="fas fa-hand-pointer text-toggle"></i>
            <span>点击展开操作菜单</span>
        </p>
    </div>
</div>

<div class="button-group" style="display:none">
    ${buttonHtml}
</div>
`;

            courseBox.addEventListener('click', () => {
                const buttons = courseBox.querySelector('.button-group');
                if (buttons.style.display === 'none') {
                    buttons.style.display = 'block';
                } else {
                    buttons.style.display = 'none';
                }
            });

            courseList.appendChild(courseBox);
            displayedCourses++; // 增加显示的课程计数
        }

        // 检查是否有课程显示
        if (displayedCourses === 0) {
            const noCoursesMessage = document.createElement('div');
            noCoursesMessage.className = 'no-courses-message';
            
            // 添加白色渐变背景和居中样式
            noCoursesMessage.style = `
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                text-align: center;
                min-height: 300px;
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                border-radius: 12px;
                padding: 30px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
                margin: 20px 0;
            `;
            
            // 添加图标和文字样式
            const iconStyle = "font-size: 48px; margin-bottom: 20px; color: #6c757d;";
            const titleStyle = "font-size: 24px; font-weight: 600; margin-bottom: 10px; color: #343a40;";
            const textStyle = "font-size: 16px; color: #6c757d; max-width: 400px; line-height: 1.6;";
            
            // 根据搜索状态显示不同的提示信息
            if (searchTerm) {
                noCoursesMessage.innerHTML = `
                    <i class="fas fa-search" style="${iconStyle}"></i>
                    <h3 style="${titleStyle}">没有找到匹配的课程</h3>
                    <p style="${textStyle}">请尝试其他搜索词或调整筛选条件</p>
                `;
            } else if (showOnlyMyCourses) {
                noCoursesMessage.innerHTML = `
                    <i class="fas fa-folder-open" style="${iconStyle}"></i>
                    <h3 style="${titleStyle}">没有找到您的课程</h3>
                    <p style="${textStyle}">${userData.role === '教师' ? 
                        '您尚未创建任何课程，请点击右上角"创建课程"按钮开始' : 
                        '您尚未被分配为任何课程的助教'}</p>
                `;
            } else {
                noCoursesMessage.innerHTML = `
                    <i class="fas fa-book-open" style="${iconStyle}"></i>
                    <h3 style="${titleStyle}">暂无可用课程</h3>
                    <p style="${textStyle}">${userData.role === '教师' ? 
                        '请创建新课程或联系管理员添加课程' : 
                        '当前没有可选的课程，请稍后再查看'}</p>
                `;
            }
            
            courseList.appendChild(noCoursesMessage);
        }

        document.getElementById('courseList').style.display = 'block';
    } catch (error) {
        console.error('获取已选课程信息失败:', error);
        
        // 创建错误提示
        const courseList = document.getElementById('courseList');
        courseList.innerHTML = '';
        
        const errorMessage = document.createElement('div');
        errorMessage.className = 'no-courses-message';
        errorMessage.innerHTML = `
            <i class="fas fa-exclamation-triangle fa-2x"></i>
            <h3>加载课程失败</h3>
            <p>${error.message || '请稍后重试'}</p>
        `;
        
        courseList.appendChild(errorMessage);
    }
}

// 选择课程
export async function selectCourse(courseCode) {
    // 检查课程是否存在
    const checkResponse = await fetch(`/check-course-code?courseCode=${courseCode}`);
    const checkData = await checkResponse.json();
    if (!checkData.exists) {
        alert('课程不存在');
        return;
    }

    // 获取所有已选课程
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const selectedCoursesResponse = await fetch(`/get-selected-courses?username=${username}`);
    if (!selectedCoursesResponse.ok) {
        alert('获取已选课程信息失败，请稍后重试');
        return;
    }
    const selectedCourses = await selectedCoursesResponse.json();

    // 检查学生是否已经选择该课程
    const isCourseSelected = selectedCourses.some(course => course.course_code === courseCode);
    if (isCourseSelected) {
        alert('你已经选择了该课程');
        return;
    }

    // 获取要选择的课程信息
    const courseResponse = await fetch(`/get-course/${courseCode}`);
    const course = await courseResponse.json();

    // 检查时间冲突
    const newCourseDay = parseInt(course.course_time.split('_')[0]);
    const newCourseStart = parseInt(course.course_time.split('_')[1].split('-')[0]);
    const newCourseEnd = parseInt(course.course_time.split('_')[1].split('-')[1]);

    for (const selectedCourse of selectedCourses) {
        const existingCourseDay = parseInt(selectedCourse.course_time.split('_')[0]);
        const existingCourseStart = parseInt(selectedCourse.course_time.split('_')[1].split('-')[0]);
        const existingCourseEnd = parseInt(selectedCourse.course_time.split('_')[1].split('-')[1]);

        if (newCourseDay === existingCourseDay &&
            ((newCourseStart >= existingCourseStart && newCourseStart <= existingCourseEnd) ||
                (newCourseEnd >= existingCourseStart && newCourseEnd <= existingCourseEnd) ||
                (existingCourseStart >= newCourseStart && existingCourseStart <= newCourseEnd) ||
                (existingCourseEnd >= newCourseStart && existingCourseEnd <= newCourseEnd))) {
            alert('课程时间冲突');
            return;
        }
    }

    // 选课成功，将选课信息保存到数据库
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const studentId = userData.user_id;

    const response = await fetch('/select-course', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            student_id: studentId,
            course_code: courseCode
        })
    });
    const result = await response.json();
    alert(result.message);
    await showCourses();
}

export async function dropCourse(courseCode) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const studentId = userData.user_id;

    const response = await fetch('/drop-course', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            student_id: studentId,
            course_code: courseCode
        })
    });
    const result = await response.json();
    alert(result.message);
    // 刷新课程列表
    await showCourses();
}

window.selectCourse = selectCourse;
window.dropCourse = dropCourse;

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href = 'success.html' + window.location.search;
        });
    }
});

// 页面加载时初始化
window.onload = async function () {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        const userResponse = await fetch(`/user-info?username=${username}`);
        const userData = await userResponse.json();
        
        // 确保 .content-header 元素存在
        const contentHeader = document.querySelector('.content-header');
        
        if (userData.role === '教师' && contentHeader) {
            const filterHtml = `
<div class="filter-container">
    <label class="filter-toggle">
        <input type="checkbox" id="myCoursesFilter" class="toggle-input">
        <span class="toggle-slider"></span>
        <span class="toggle-text">我创建的课程</span>
    </label>
</div>
`;
            contentHeader.insertAdjacentHTML('beforeend', filterHtml);
            
            // 添加事件监听器
            document.getElementById('myCoursesFilter').addEventListener('change', function() {
                showCourses();
            });
        } else if (userData.role === '助教' && contentHeader) {
            const filterHtml = `
<div class="filter-container">
    <label class="filter-toggle">
        <input type="checkbox" id="myCoursesFilter" class="toggle-input">
        <span class="toggle-slider"></span>
        <span class="toggle-text">我负责的课程</span>
    </label>
</div>
`;
            contentHeader.insertAdjacentHTML('beforeend', filterHtml);
            
            // 添加事件监听器
            document.getElementById('myCoursesFilter').addEventListener('change', function() {
                showCourses();
            });
        }
        
        await showCourses();
    } catch (error) {
        console.error('初始化失败:', error);
    }
};

export async function checkTutorPermission(tutorId, courseCode) {
    const response = await fetch(`/check-tutor-permission?tutor_id=${tutorId}&course_code=${courseCode}`);
    const data = await response.json();
    return data.hasPermission;
}

// 添加搜索过滤函数
export function filterCourses() {
    // 使用防抖避免频繁刷新
    if (filterDebounceTimer) {
        clearTimeout(filterDebounceTimer);
    }
    
    filterDebounceTimer = setTimeout(() => {
        showCourses();
    }, 150); // 防抖延迟
}

// 添加到全局作用域
window.filterCourses = filterCourses;

export function getFileColorClass(extension) {
    const colorMap = {
        pdf: 'text-red-500',
        doc: 'text-blue-500',
        docx: 'text-blue-500',
        xls: 'text-green-500',
        xlsx: 'text-green-500',
        ppt: 'text-orange-500',
        pptx: 'text-orange-500',
        default: 'text-gray-500'
    };
    return colorMap[extension] || colorMap.default;
}

export function escapeHTML(str) {
    return str.replace(/[&<>"']/g, function (match) {
    switch (match) {
    case '&':
    return '&amp;';
    case '<':
    return '&lt;';
    case '>':
    return '&gt;';
    case '"':
    return '&quot;';
    case "'":
    return '&#039;';
}
 });
}